package io.codescience.aianaly.service;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;

@Service
public class DeepseekService {

    @Value("${deepseek.api.key}")
    private String apiKey;

    @Value("${deepseek.api.url}")
    private String apiUrl;

    private final WebClient webClient;

    public DeepseekService(WebClient.Builder webClientBuilder) {
        this.webClient = webClientBuilder.build();
    }

    public String analyzeResume(String resumeText) {
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("model", "deepseek-chat");

        Map<String, Object> message = new HashMap<>();
        message.put("role", "user");
        message.put("content", "请分析以下简历内容，给出综合评价、技能分析、工作经验评价和改进建议：\n\n" + resumeText);

        requestBody.put("messages", new Map[]{message});
        requestBody.put("temperature", 0.7);
        requestBody.put("max_tokens", 2000);

        try {
            Map<String, Object> response = webClient.post()
                    .uri(apiUrl)
                    .header(HttpHeaders.AUTHORIZATION, "Bearer " + apiKey)
                    .header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE)
                    .bodyValue(requestBody)
                    .retrieve()
                    .bodyToMono(Map.class)
                    .block();

            if (response != null && response.containsKey("choices")) {
                Map<String, Object> choice = ((java.util.List<Map<String, Object>>) response.get("choices")).get(0);
                Map<String, Object> messageResponse = (Map<String, Object>) choice.get("message");
                return (String) messageResponse.get("content");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "分析过程中出现错误: " + e.getMessage();
        }

        return "未能获取到分析结果";
    }
}